package br.ita.redecasd.mi.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.ita.redecasd.mi.ws.SessionHandlerWSProxy;

/**
 * Servlet implementation class for Servlet: SearchPatientServlet
 *
 */
 public class SearchPatientServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    /**
	 * 
	 */
	private static final long serialVersionUID = 9174052546332203744L;

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public SearchPatientServlet() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		if ( request.getSession() != null && request.getSession().getAttribute("username") != null)
		{
			String username = (String)request.getSession().getAttribute("username");
			String sessionID = (String)request.getSession().getAttribute("sessionID");
			SessionHandlerWSProxy proxy = new SessionHandlerWSProxy();
	        boolean sessionValid = proxy.validateSession(sessionID, username);
	        if ( sessionValid )
	        {
	        	String login = request.getParameter("login");
	        	if ( login == null )
	        	{
	        		login = (String) request.getSession().getAttribute("patientName");
	        		request.getSession().removeAttribute("patientName");
	        	}	        	
	        	if (proxy.mustAuthenticate(username, login))
	        	{
	        		request.getSession().setAttribute("patientName", login);
	        		RequestDispatcher view = request.getRequestDispatcher("acl_form.jsp");
	        		view.forward(request, response);
	        		return;
	        	}
	        	String[] patientInfo = proxy.getPatientDetails(login);
	        	if ( patientInfo != null )
	        	{
	        		request.setAttribute("login", login);
	        		request.setAttribute("displayName", patientInfo[1]);
	        		request.setAttribute("phoneNumber", patientInfo[2]);
	        		request.setAttribute("address", patientInfo[3]);
	        		RequestDispatcher view = request.getRequestDispatcher("info.jsp");
	        		view.forward(request,response);
	        		return;
	        	}
	        }
	        
		}
		
		RequestDispatcher view = request.getRequestDispatcher("welcome.jsp");
		view.forward(request, response);
		
		
			
    	
        
        
	}
	
 }